/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.goods.appweb;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.jeesite.common.responseReturn.entity.ResultObject;
import com.jeesite.common.responseReturn.utils.CommonUtils;
import com.jeesite.common.responseReturn.web.Render;
import com.jeesite.common.utils.CommonPath;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.config.MyProps;
import com.jeesite.modules.goods.entity.ZtGoimg;
import com.jeesite.modules.goods.service.ZtGoimgService;
import com.jeesite.modules.jdProduct.utils.ProductPoolUtils;
import com.jeesite.modules.util.AliRequestUtils;

/**
 * 测试数据Controller
 * 
 * @author ThinkGem
 * @version 2018-04-22
 */
@Controller
@RequestMapping(value = "${frontPath}/ztGoimg")
public class AppZtGoimgController extends BaseController {

	@Autowired
	private ZtGoimgService ztGoimgService;
	
	@Autowired
	private MyProps myProps;

	/**
	 * 获取中间logo图片
	 */
	@ResponseBody
	@RequestMapping(value = "getLogoimg")
	public void list(HttpServletRequest request, HttpServletResponse response) {
			
		String paramStr=CommonUtils.getParams(request);
		
		JSONObject jo=JSONObject.parseObject(paramStr);
		String adminid = jo.getString("adminid");
		
		ResultObject res = new ResultObject();
		
		
		ZtGoimg ztGoimg=ztGoimgService.getFirst();
		
		String img = "";
		try {
			img = myProps.getServerPath() + ztGoimgService.getImgFirst(ztGoimg);
		} catch (Exception ex) {
			img = "";
		}
		
		res.setResult(200L);
		res.setData(img);
		Render.renderString(response, res);
	}

	
	
	/**
	 * 图片上传 文章上传
	 * 
	 * @return
	 * @throws Exception
	 *//*
	// @ExcLoginInterceptor 自定义的拦截器注解
	@ResponseBody
	@RequestMapping(value = "/uploadImg")
	public void uploadImg(HttpServletRequest request,MultipartFile file,
			HttpServletResponse response)  {
		
		ResultObject res = new ResultObject();
		long message = 200L;
		String schemeUrl = request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort()+"/zt";   //http://localhost:8086/zt
		
		
		// 获取文件需要上传到的路径
		// String path = request.getServletContext().getRealPath("/upload")+"/";
		String path = request.getSession().getServletContext().getRealPath("")
				+ CommonPath.getDestFolder(request) + "/";
		
		System.out.println("--------------"+path);
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		System.out.println("----5555----------");
		Map<String,String> map=new HashMap<String,String>();
		try {
			request.setCharacterEncoding("utf-8"); // 设置编码
			// 获得磁盘文件条目工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// 如果没以下两行设置的话,上传大的文件会占用很多内存，
			// 设置暂时存放的存储室,这个存储室可以和最终存储文件的目录不同
			factory.setRepository(dir);
			// 设置缓存的大小，当上传文件的容量超过该缓存时，直接放到暂时存储室
			factory.setSizeThreshold(1024 * 1024);
			// 文件上传处理
			ServletFileUpload fileUpload = new ServletFileUpload(factory);
			List<FileItem> list = fileUpload.parseRequest(request);
			
			System.out.println("----5555-66666---------");
		//	for (FileItem item : list) {
				System.out.println("----5555-66666777777---------");
				// 获取表单的属性名字
				String name = file.getOriginalFilename();
				// 如果获取的表单信息是普通的 文本 信息
				
					System.out.println("----5555-66666777777-888888888999999999999999--------"+file.getSize());
				
					// 根据当前时间生成图片的名称（需要自己封装写方法--当然也可以按自己的规则生成图片名称）

					String fileName = UUID.randomUUID().toString() + ".jpg";

					// 自定义上传图片的名字
					// String fileName = pictureName+".jpg";

					String destPath = path + fileName;
					
					System.out.println("---------666-----"+destPath);
					// 此处可以保存与数据库，代码省略……
					
					//map.put(name, schemeUrl+destPath);
					
					// 真正写到磁盘上
					File f = new File(destPath);
					if(!f.exists()){
						f.createNewFile();
					}
					
					OutputStream out = new FileOutputStream(f);
					InputStream in = file.getInputStream();
					int length = 0;
					byte[] buf = new byte[1024];
					// in.read(buf) 每次读到的数据存放在buf 数组中
					while ((length = in.read(buf)) != -1) {
						// 在buf数组中取出数据写到（输出流）磁盘上
						out.write(buf, 0, length);
					}
					message = 200L;
					System.out.println("---------7777-----"+schemeUrl+destPath);
					in.close();
					out.close();
					System.out.println("-----link------"+schemeUrl+destPath);
					res.setData((schemeUrl+destPath).replace("/wewoo/usr/local/tomcat8081/webapps", ""));// 图片地址
	//http://47.106.100.142:8086/zt/usr/local/tomcat8086/webapps/zt/userfiles/images/2018/8/22/1c9e254f-9792-4a93-abc4-52e375fc3df4.jpg
		//	}
			

		} catch (FileUploadException e1) {
			logger.error("", e1);
			message = 400L;
		} catch (Exception e) {
			logger.error("", e);
			message = 400L;
		}

		res.setResult(message);
		Render.renderString(response, res);
	}
	*/
	
	public String resultImg;
	public String fileName;
	
	@ResponseBody
	@RequestMapping(value = "/uploadImg")
	public void uploadImg(HttpServletRequest request,MultipartFile file,
			HttpServletResponse response)  {
		
		ResultObject res = new ResultObject();
		long message = 200L;
		String schemeUrl = myProps.getServerPath()+"/sk";
		//request.getServerName() + 

		// 获取文件需要上传到的路径
		// String path = request.getServletContext().getRealPath("/upload")+"/";
		String path = request.getSession().getServletContext().getRealPath("")
				+ CommonPath.getDestFolder(request) + "/";
		
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		
		Map<String,String> map=new HashMap<String,String>();
		try {
			request.setCharacterEncoding("utf-8"); // 设置编码
			// 获得磁盘文件条目工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// 如果没以下两行设置的话,上传大的文件会占用很多内存，
			// 设置暂时存放的存储室,这个存储室可以和最终存储文件的目录不同
			factory.setRepository(dir);
			// 设置缓存的大小，当上传文件的容量超过该缓存时，直接放到暂时存储室
			factory.setSizeThreshold(1024 * 1024);
			// 文件上传处理
			ServletFileUpload fileUpload = new ServletFileUpload(factory);
			List<FileItem> list = fileUpload.parseRequest(request);
			
		
				// 获取表单的属性名字
				String name = file.getOriginalFilename();
				// 如果获取的表单信息是普通的 文本 信息				
					// 根据当前时间生成图片的名称（需要自己封装写方法--当然也可以按自己的规则生成图片名称）

					 fileName = UUID.randomUUID().toString() + ".jpg";

					// 自定义上传图片的名字
					// String fileName = pictureName+".jpg";

					String destPath = path + fileName;
					
				
					// 此处可以保存与数据库，代码省略……
					
					//map.put(name, schemeUrl+destPath);
					
					// 真正写到磁盘上
					File f = new File(destPath);
					if(!f.exists()){
						f.createNewFile();
					}
					
					OutputStream out = new FileOutputStream(f);
					InputStream in = file.getInputStream();
					int length = 0;
					byte[] buf = new byte[1024];
					// in.read(buf) 每次读到的数据存放在buf 数组中
					while ((length = in.read(buf)) != -1) {
						// 在buf数组中取出数据写到（输出流）磁盘上
						out.write(buf, 0, length);
					}
					message = 200L;
					
					in.close();
					out.close();
				
					 resultImg=(schemeUrl+destPath).replace("/sk/usr/local/tomcat8081/webapps", "");
					  ExecutorService cachedThreadPool=ProductPoolUtils.cachedThreadPool;
				        if(cachedThreadPool==null){
				        	cachedThreadPool=Executors.newCachedThreadPool();
				        }

								cachedThreadPool.execute(new Runnable() {			
									@Override
									public void run() {
										// TODO Auto-generated method stub
										try{
											
											AliRequestUtils.uploadFile(resultImg, fileName,"linghu365");
										}catch(Exception ex){}
									}
								});
					
					res.setData("https://linghu365.oss-cn-shenzhen.aliyuncs.com/"+fileName);// 图片地址
	
		} catch (FileUploadException e1) {
			logger.error("", e1);
			message = 400L;
		} catch (Exception e) {
			logger.error("", e);
			message = 400L;
		}

		res.setResult(message);
		Render.renderString(response, res);
	}
	
	
	/**
	 * 图片上传 文章上传
	 * 
	 * @return
	 * @throws Exception
	 */
	// @ExcLoginInterceptor 自定义的拦截器注解
	@ResponseBody
	@RequestMapping(value = "/uploadImgQcode")
	public void uploadImgQcode(HttpServletRequest request,
			HttpServletResponse response) {
		ResultObject res = new ResultObject();
		long message = 200L;
		
		String schemeUrl="https://sk.linghu365.com/sk";
		
		//request.getServerName() + 

		// 获取文件需要上传到的路径
		// String path = request.getServletContext().getRealPath("/upload")+"/";
		String path = request.getSession().getServletContext().getRealPath("")
				+ CommonPath.getDestFolder(request) + "/";

		File dir = new File(path);

		if (!dir.exists()) {
			dir.mkdirs();
		}
		Map<String, String> map = new HashMap<String, String>();
		try {
			request.setCharacterEncoding("utf-8"); // 设置编码
			// 获得磁盘文件条目工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// 如果没以下两行设置的话,上传大的文件会占用很多内存，
			// 设置暂时存放的存储室,这个存储室可以和最终存储文件的目录不同
			factory.setRepository(dir);
			// 设置缓存的大小，当上传文件的容量超过该缓存时，直接放到暂时存储室
			factory.setSizeThreshold(1024 * 1024);
			// 文件上传处理
			ServletFileUpload fileUpload = new ServletFileUpload(factory);
			List<FileItem> list = fileUpload.parseRequest(request);
			FileItem picture = null;
		
			for (FileItem item : list) {
				// 获取表单的属性名字
				String name = item.getFieldName();
				
			
				// 如果获取的表单信息是普通的 文本 信息
				if (item.isFormField()) {
					// 获取用户具体输入的字符串
					String value = item.getString();
					map.put(name, value);
				} else {
					picture = item;
					
					// 根据当前时间生成图片的名称（需要自己封装写方法--当然也可以按自己的规则生成图片名称）
					
					String fileName = UUID.randomUUID().toString() + ".jpg";
					// /rtedu/resource/images/2018/1/25/d6281117-f19b-4d9b-a833-267e2447363e.jpg
					// 自定义上传图片的名字
					// String fileName = pictureName+".jpg";

					String destPath = path + fileName;
					// 此处可以保存与数据库，代码省略……

					// map.put(name, schemeUrl+destPath);

					// 真正写到磁盘上
					File file = new File(destPath);
					OutputStream out = new FileOutputStream(file);
					InputStream in = picture.getInputStream();
					int length = 0;
					byte[] buf = new byte[1024];
					// in.read(buf) 每次读到的数据存放在buf 数组中
					while ((length = in.read(buf)) != -1) {
						// 在buf数组中取出数据写到（输出流）磁盘上
						out.write(buf, 0, length);
					}
					message = 200L;
					in.close();
					out.close();
					
					String re = schemeUrl + destPath;
					String tpurl=re.replaceAll(
							"/usr/local/tomcat8081/webapps/wewoo", "");// 图片地址
					
					String imgPath = System.getProperty("catalina.home")
							+ "/webapps/wewoo/imgfile/";
					String imgName = "tqcode" +System.currentTimeMillis()
							+ ".png";
					File f = new File(imgPath);
					if (!f.exists()) {
						try {
							f.mkdirs();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					boolean ss = getQrcodeImg(tpurl, imgPath + imgName);
					String qcode = "https://wewoo.gzyuejiang.com/wewoo/imgfile/" + imgName;
					
					res.setData(qcode);
					res.setResult(200L);

					Render.renderString(response, res);
					return;
				}
			}

		} catch (FileUploadException e1) {
			logger.error("", e1);
			message = 400L;
		} catch (Exception e) {
			logger.error("", e);
			message = 400L;
		}
		
		res.setResult(message);
		Render.renderString(response, res);
	}
	
		
	public static boolean getQrcodeImg(String content, String path) {
		boolean isResult = true;
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();

		hints.put(EncodeHintType.MARGIN, 0);
		try {
			BitMatrix bitMatrix = new QRCodeWriter().encode(content,

			BarcodeFormat.QR_CODE, 256, 256, hints);

			// 1.1去白边

			int[] rec = bitMatrix.getEnclosingRectangle();

			int resWidth = rec[2] + 1;

			int resHeight = rec[3] + 1;

			BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);

			resMatrix.clear();

			for (int i = 0; i < resWidth; i++) {

				for (int j = 0; j < resHeight; j++) {

					if (bitMatrix.get(i + rec[0], j + rec[1])) {

						resMatrix.set(i, j);

					}

				}

			}

			// 2

			int width = resMatrix.getWidth();

			int height = resMatrix.getHeight();

			BufferedImage image = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_ARGB);

			for (int x = 0; x < width; x++) {

				for (int y = 0; y < height; y++) {

					image.setRGB(x, y, resMatrix.get(x, y) == true ?

					Color.BLACK.getRGB() : Color.WHITE.getRGB());

				}

			}

			// 3

			ImageIO.write(image, "png", new File(path));
			isResult = true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			isResult = false;
		}
		return isResult;
	}
}